package initialize

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"shop_srv/user_srv/internal/global"
)

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}

func InitConfig() {
	prod := GetEnvInfo("DEBUG")
	configPath := ""
	if prod {
		configPath = "user_srv/config-prod.yaml"
	}
	configPath = "user_srv/config-dev.yaml"
	v := viper.New()
	v.SetConfigFile(configPath)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	sc := global.ServerConfig
	if err := v.Unmarshal(&global.ServerConfig); err != nil {
		panic(err)
	}
	zap.S().Infof("配置信息:%v", global.ServerConfig)
	//viper的功能 动态监听配置的变化
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file changed:", in.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&sc)
	})
}
